package com.example.quartz.config;

import com.example.quartz.app.dao.JobDao;
import com.example.quartz.app.entity.JobEntity;
import com.example.quartz.util.Utils;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.spi.JobFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.annotation.Resource;
import java.util.List;

@Configuration
public class SchedulerConfig {

    @Resource
    private JobDao jobDao;

    @Bean
    public JobFactory jobFactory(ApplicationContext applicationContext) {
        AutowiringSpringBeanJobFactory jobFactory = new AutowiringSpringBeanJobFactory();
        jobFactory.setApplicationContext(applicationContext);
        return jobFactory;
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(JobFactory jobFactory) throws Exception {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        factory.setOverwriteExistingJobs(true);
        factory.setJobFactory(jobFactory);
        factory.afterPropertiesSet();
        return factory;
    }

    @Bean
    public Scheduler scheduler(SchedulerFactoryBean schedulerFactoryBean) throws SchedulerException{
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        List<JobEntity> list = jobDao.getJobList();
        for(JobEntity entity : list){
            scheduler.scheduleJob(Utils.getJobDetail(entity), Utils.getCronTrigger(entity));
        }
        return scheduler;
    }
}
